package com.soboot.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soboot.base.converter.BeanMapping;
import com.soboot.base.enums.DeleteStatus;
import com.soboot.system.entity.SysMenu;
import com.soboot.system.exception.ResCode;
import com.soboot.system.exception.SystemException;
import com.soboot.system.mapper.SysMenuMapper;
import com.soboot.system.model.MenuSaveReqModel;
import com.soboot.system.model.QueryMenuListReqModel;
import com.soboot.system.service.ISysMenuService;
import com.soboot.system.vo.MenuVO;
import com.soboot.system.vo.QueryMenuListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author:
 * @createTime: 2022年09月26日 21:18:21
 * @version:
 * @Description:
 * @Copyright:
 */
@Service
public class MenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<QueryMenuListVO> getListByUserId(Integer userId) {

        return sysMenuMapper.getMenuListByUserId(userId);
    }

    @Override
    public IPage<MenuVO> page(QueryMenuListReqModel reqModel) {
        return null;
    }

    @Override
    public List<MenuVO> getList() {

        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted","0");
        List<SysMenu> list = sysMenuMapper.selectList(wrapper);
        return BeanMapping.mapList(list,MenuVO.class);
    }

    @Override
    public MenuVO detail(Integer id) {

        SysMenu sysMenu = sysMenuMapper.selectById(id);
        return BeanMapping.map(sysMenu,MenuVO.class);
    }

    @Override
    public void delete(Integer id) {

        int childs = sysMenuMapper.selectCount(Wrappers.<SysMenu>lambdaQuery().eq(SysMenu::getParentId, id));
        if(childs>0){
            throw new SystemException(ResCode.FAIL,"当前菜单下存在子菜单不能删除!");
        }

        UpdateWrapper<SysMenu> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",id).set("deleted", DeleteStatus.DELETE.getValue());
        sysMenuMapper.update(null,wrapper);
    }
}
